//  store.js 中都mutation中增加添加和删除token的方法
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = { // 全局管理的数据存储
    
    orders:[],
    
    isLogin:sessionStorage.getItem('token') ? true : false,
    //用户名称或者未登录
    condition:sessionStorage.getItem('nickname') ? sessionStorage.getItem('nickname') :'未登录',
    //token
    token: sessionStorage.getItem('token') ? sessionStorage.getItem('token') : '', // token
    //用户头像
    img:sessionStorage.getItem('img') ? sessionStorage.getItem('img') : "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png", 
};

export default new Vuex.Store({

    state,
    mutations: {
        $_setToken(state, value) { // 设置存储token
            state.token = value;
            sessionStorage.setItem('token', value);
        },
        //登录
        $_setUser(state,user){
            state.condition = user.nickname
            state.isLogin=true
            sessionStorage.setItem("account",user.account)
            sessionStorage.setItem("nickname",user.nickname)
            sessionStorage.setItem("role",user.role)
            state.img = Vue.prototype.imgUrl+"/api/public/showImg/"+user.img
            sessionStorage.setItem("img",Vue.prototype.imgUrl+"/api/public/showImg/"+user.img)
            if(user.img==null){
                state.img ="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
                sessionStorage.setItem("img","https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png")
            }
        },
        //修改头像
        $_setImg(state,uuid){
            state.img = Vue.prototype.imgUrl+"/api/public/showImg/"+uuid
            sessionStorage.setItem("img",Vue.prototype.imgUrl+"/api/public/showImg/"+uuid)
        },
        //用户修改名字
        $_setNickname(state,nickname){
            state.condition = nickname
            sessionStorage.setItem("nickname",nickname)
        },
        // 退出登录,删除token和用户信息
        $_removeStorage(state) { 
            sessionStorage.clear();
            state.condition = "未登录"
            state.img ="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
            state.isLogin=false
            console.log(state.img);
        },
        //购物车选中的商品
        $_setOrders(state,val){
            for (const key in val) {
                state.orders.push(val[key])
            }
        }
    }
})